package com.hanter.android.radwidget.recyclerview;

import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.view.GestureDetectorCompat;
import androidx.recyclerview.widget.RecyclerView;

abstract public class OnItemClickListener extends RecyclerView.SimpleOnItemTouchListener {

    private RecyclerView recyclerView;
    @NonNull
    private GestureDetectorCompat gestureDetector;

    public OnItemClickListener(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
        this.gestureDetector = new GestureDetectorCompat(recyclerView.getContext(),
                new GestureDetector.SimpleOnGestureListener() {
                    @Override
                    public boolean onSingleTapUp(MotionEvent e) {
                        return true;
                    }

                    @Override
                    public void onLongPress(MotionEvent e) {
                        View childView = com.hanter.android.radwidget.recyclerview.OnItemClickListener.this.recyclerView.findChildViewUnder(e.getX(), e.getY());
                        if (childView != null) {
                            onItemLongClick(childView, OnItemClickListener.this.recyclerView.getChildAdapterPosition(childView));
                        }
                    }
                });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
        View childView = rv.findChildViewUnder(e.getX(), e.getY());
        if (childView != null && gestureDetector.onTouchEvent(e)) {
            onItemClick(childView, rv.getChildAdapterPosition(childView));
            return false;
        }
        return false;
    }

    public abstract void onItemClick(View view, int position);

    public abstract void onItemLongClick(View view, int position);

}